<template>
    <teleport to="#BreadcrumbTeleportText"><span class="fz14">（{{ listAllTotal }}）</span></teleport>
    <ul class="f-e-b pa12">
        <li>
            <el-button v-if="!isGroupManagementPage" class="mr12" type="primary" :icon="Plus" @click="showDialogAddMember">新增会员</el-button>
            <el-dropdown popper-class="dropdown__item--center">
                <el-button type="primary">
                    <span>{{ exportConfig.title }}&nbsp;</span>
                    <el-icon>
                        <ArrowDown/>
                    </el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item v-for="row in exportDropdown" :key="row.value" @click="showExportDialog(row)">
                            {{ row.label }}
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </li>
        <li class="f-c">
            <GFilterTime :type="componentType" :value="params" @change="mdSearch"/>
            <GSearch :type="componentType" :value="params" @change="mdSearch" class="ml12"/>
        </li>
    </ul>

    <el-table
        border-t
        v-loading="tableLoading"
        :data="tableData"
        :empty-text="emptyText"
        @sort-change="tableSortChange"
        :default-sort="defaultSort"
        class="table-loading-mask-body"
    >
        <el-table-column fixed="left" align="center" label="头像" width="60">
            <template #default="{ row }">
                <div class="f-c-c">
                    <el-image class="table-avatar" :src="row.avatar">
                        <template #error>
                            <el-image src="https://cdn.zhimatech.com/wechatjigou-default-header-three.png"/>
                        </template>
                    </el-image>
                </div>
            </template>
        </el-table-column>
        <el-table-column fixed="left" label="会员昵称" width="150" show-overflow-tooltip>
            <template #default="{ row }">{{ row.nickname || `用户${row.mobile}` }}</template>
        </el-table-column>
        <el-table-column fixed="left" property="mobile" label="会员手机号" width="135"/>
        <el-table-column label="会员卡号" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">{{ row.sn || '--' }}</template>
        </el-table-column>
        <el-table-column property="gender" label="性别" min-width="70">
            <template #default="{ row }">{{ genderLabel[row.gender] || '--' }}</template>
        </el-table-column>
        <el-table-column label="生日" min-width="100">
            <template #default="{ row }">{{ row.birthday || '--' }}</template>
        </el-table-column>
        <el-table-column label="地区" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
                <span v-if="row.province">{{ row.province }}{{ row.city }}</span>
                <span v-else>--</span>
            </template>
        </el-table-column>
        <el-table-column label="积分" min-width="100" property="balance" sortable="custom">
            <template #default="{ row }">
                <span v-if="row.balance || row.balance === 0">{{ row.balance }}</span>
                <span v-else>--</span>
            </template>
        </el-table-column>
        <el-table-column label="消费金额" min-width="120" property="cost" sortable="custom">
            <template #default="{ row }">
                <span v-if="row.cost || row.cost === 0">{{ row.cost }}</span>
                <span v-else>0.00</span>
            </template>
        </el-table-column>
        <el-table-column min-width="150" show-overflow-tooltip>
            <template #header>
                <GTableHeadSelect
                    name="会员等级"
                    :props="{ value: 'id', label: 'name' }"
                    :filters="levelFilters"
                    v-model="filterLevelId"
                    @change="resetPageTableList"
                />
            </template>
            <template #default="{ row }">{{ row.level_name || '--' }}</template>
        </el-table-column>
        <el-table-column label="会员标签" min-width="160" property="labels" show-overflow-tooltip/>
        <el-table-column v-if="isPaidMember" min-width="110">
            <template #header>
                <GTableHeadSelect
                    name="付费会员"
                    :filters="premiumStatus"
                    v-model="params.premium_status"
                    @change="resetPageTableList"
                />
            </template>
            <template #default="{ row }">
                <span>{{ premiumStatusLabel[row.premium_status] || '--' }}</span>
            </template>
        </el-table-column>
        <el-table-column v-if="isPaidMember" label="到期时间" min-width="160" property="premium_end_at" sortable="custom">
            <template #default="{ row }">{{ row.premium_end_at || '--' }}</template>
        </el-table-column>
        <el-table-column label="上传照片" min-width="90">
            <template #default="{ row }">{{ row.photo ? '已上传' : '未上传' }}</template>
        </el-table-column>
        <el-table-column v-if="!isGroupManagementPage" label="微信无感积分" min-width="120">
            <template #default="{ row }">{{ +row.wechat_quick_point === 1 ? '开通' : '未开通' }}</template>
        </el-table-column>
        <el-table-column v-if="!isGroupManagementPage" label="支付宝无感积分" min-width="120">
            <template #default="{ row }">{{ +row.alipay_quick_point === 1 ? '开通' : '未开通' }}</template>
        </el-table-column>
        <el-table-column v-if="!isGroupManagementPage" label="商场入会时间" min-width="160" property="created_at" sortable="custom">
            <template #default="{ row }">{{ row.created_at || '--' }}</template>
        </el-table-column>
        <el-table-column v-if="isGroupManagementPage" label="入会商场" min-width="150" property="mall_name" show-overflow-tooltip/>
        <el-table-column v-if="isGroupManagementPage" label="集团入会时间" min-width="160" property="created_at" sortable="custom">
            <template #default="{ row }">{{ row.company_joined_at || row.created_at || '--' }}</template>
        </el-table-column>
        <el-table-column width="80" fixed="right">
            <template #header><span class="pl10">状态</span></template>
            <template #default="{ row }">
                <div class="f-c">
                    <span class="status-sign" :style="{ backgroundColor: memberStatusColor[row.status] }"/>
                    <span>{{ memberStatusLabel[row.status] || '--' }}</span>
                </div>
            </template>
        </el-table-column>
        <el-table-column width="230" fixed="right">
            <template #header><span class="pl3">操作</span></template>
            <template #default="{ row }">
                <div v-if="row.status !== 2" class="f-c">
                    <el-button link type="primary" @click="routerDetail(row.id)">查看</el-button>
                    <el-button link type="primary" @click="showEditModel(row)">编辑</el-button>
                    <el-button link type="primary" @click="routerTagging(row.id)">打标签</el-button>
                    <div v-if="(isUniqueMember && isGroupManagementPage) || !isUniqueMember" class="f-c ml12">
                        <el-button v-if="row.status === 1" link type="danger" @click="showBlackModel(row)">移入黑名单</el-button>
                        <el-button v-else link type="primary" @click="showBlackModel(row)">移出黑名单</el-button>
                    </div>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <div class="f-d-c pv15">
        <GPagination
            :current-page="params.page"
            :page-size="params.per_page"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <EditMember v-model="dialogAddMember" :detail="memberDetail" @update="getListLoading" @add="resetPageTableList"/>

    <BlackListModel v-model="blackParams.dialog" :status="blackParams.status" :member-id="blackParams.memberId" @change="getListLoading"/>
</template>

<script setup lang="ts">
    import { ref, onMounted, reactive } from "vue";
    import { ElMessage } from "element-plus";
    import { Plus, ArrowDown } from "@element-plus/icons-vue";
    import { useRoute, useRouter } from "vue-router";

    import EditMember from "@/views/MemberManage/MemberList/components/EditMember.vue"
    import BlackListModel from "@/views/MemberManage/MemberList/components/BlackListModel.vue";

    import { _mallStore } from "@/store/config";
    import { storeToRefs } from "pinia";
    import { FilterTimesRow } from "@/components/globalUtils/GFilterTime";
    import { postV3ApiMemberList, getRestfulMallMembers } from "@/assets/api";
    import { getRestfulMallLevelsFilter } from "@/assets/api/handler";
    import { FGenderLabel, FPremiumStatus, FPremiumStatusLabel, FMemberStatusColor, FMemberStatusLabel } from "@/filters";
    import { TypeTableSort, TypeSortParams, getTableSortOrder } from "@/utils/handlerData";
    import { $getMountedParams, $setParamsStorage } from "@/utils/storage";
    import { TypeFilters } from "@/interface/filters";
    import { TypeExport } from "@/interface/export";

    const { isPaidMember, isUniqueMember, isGroupManagementPage } = storeToRefs(_mallStore);
    const route = useRoute();
    const router = useRouter();

    const genderLabel = ref<ObjValueStr>(FGenderLabel);

    const premiumStatus = ref<TypeFilters.filter[]>(FPremiumStatus);
    const premiumStatusLabel = ref<ObjValueStr>(FPremiumStatusLabel);

    const memberStatusLabel = ref<ObjValueStr>(FMemberStatusLabel);
    const memberStatusColor = ref<ObjValueStr>(FMemberStatusColor);

    const componentType = ref<string>('member');
    let emptyText = ref<string>('');
    let tableLoading = ref<boolean>(false);
    let tableData = ref<ObjValueAny[]>([]);
    let listAllTotal = ref<number>(0);
    let total = ref<number>(0);
    let params = reactive<ObjValueAny>({
        page: 1,
        per_page: 15,
        order_by: '',
        sort: '',
        premium_status: '',
    });
    // 会员等级筛选
    const searchLevelKey = isGroupManagementPage.value ? 'member_level_id' : 'level_id';
    let filterLevelId = ref<string>('');
    params[searchLevelKey] = '';

    onMounted(() => {
        const resp = $getMountedParams(componentType.value, params);
        if (resp.page) {
            filterLevelId.value = params[searchLevelKey];
            defaultSort.value.prop = params.order_by || '';
            defaultSort.value.order = params.sort ? `${params.sort}ending` : '';
        }
        getLevelList();
        getListAllTotal();
        getTableList();
    })

    // 排序
    const defaultSort = ref<TypeTableSort>({ prop: '', order: '' });
    const tableSortChange = ({ order, prop }: TypeTableSort) => {
        const paramsSort: TypeSortParams = getTableSortOrder(order, prop);
        params = Object.assign(params, paramsSort);
        resetPageTableList();
    }
    // 日期/关键字 搜索
    const mdSearch = (row: FilterTimesRow) => {
        params = Object.assign(params, row);
        resetPageTableList();
    }
    // 选择 每页条数
    const handleSizeChange = (num: number) => {
        params.per_page = num;
        resetPageTableList();
    }
    const resetPageTableList = () => {
        handleCurrentChange();
    }
    // 分页
    const handleCurrentChange = (page: number = 1) => {
        params.page = page;
        getListLoading();
    }
    // 列表请求 loading
    const getListLoading = () => {
        tableLoading.value = true;
        getTableList();
    }
    // 会员列表
    const getTableList = () => {
        emptyText.value = '加载中...';
        params[searchLevelKey] = filterLevelId.value;
        if (isGroupManagementPage.value) {
            params.company_id = _mallStore.companyId;
            postV3ApiMemberList(params, { noRepeat: 1 }).then((resp: ObjValueAny) => {
                handlerTableList(resp);
            });
        } else {
            getRestfulMallMembers(params, { noRepeat: 1 }).then((resp: ObjValueAny) => {
                handlerTableList(resp);
            });
        }
    }
    const handlerTableList = (resp: ObjValueAny) => {
        if (resp.code === 200) {
            const { data } = resp;
            for (let row of data) {
                let text: string = '--';
                if (row.labels && row.labels.length) {
                    if (row.labels.length < 5) {
                        text = row.labels.join(',');
                    } else {
                        text = `${row.labels[0]},${row.labels[1]},${row.labels[2]},${row.labels[3]}...`;
                    }
                }
                row.labels = text;
            }
            tableData.value = data;
            total.value = resp.meta?.total || 0;
        } else {
            ElMessage.error(resp.msg);
        }
        emptyText.value = '暂无数据';
        tableLoading.value = false;
    }
    // 会员总数
    const getListAllTotal = async () => {
        const totalParams: ObjValueAny = { page: 1, per_page: 0 };
        let resp: ObjValueAny;
        if (isGroupManagementPage.value) {
            totalParams.company_id = _mallStore.companyId;
            resp = await postV3ApiMemberList(totalParams);
        } else {
            resp = await getRestfulMallMembers(totalParams);
        }
        listAllTotal.value = resp.meta?.total || 0;
    }
    // 获取会员等级列表
    let levelFilters = ref<TypeFilters.filterApi[]>([]);
    const getLevelList = async () => {
        levelFilters.value = await getRestfulMallLevelsFilter();
    }

    // 查看
    const routerDetail = (id: number) => {
        $setParamsStorage(params);
        router.push({
            name: 'MemberDetail',
            params: { id },
        })
    }
    // 打标签
    const routerTagging = (id: number) => {
        router.push({
            name: 'MemberTagging',
            params: { id },
        })
    }
    // 新增/编辑
    let memberDetail = ref<ObjValueAny>({});
    // 显示新增会员 弹窗
    let dialogAddMember = ref<boolean>(false);
    const showDialogAddMember = () => {
        memberDetail.value = {};
        dialogAddMember.value = true;
    }
    // 显示编辑会员 弹窗
    const showEditModel = (row: { id: number }) => {
        memberDetail.value = row;
        dialogAddMember.value = true;
    }
    // 移入黑名单/移出黑名单
    const blackParams = reactive<{ dialog: boolean, status: number, memberId: number }>({
        dialog: false,
        status: 0,
        memberId: 0,
    })
    const showBlackModel = (row: { dialog: boolean, status: number, id: number }) => {
        blackParams.dialog = true;
        blackParams.status = row.status;
        blackParams.memberId = row.id;
    }

    // 导出
    const ExportModelRef = ref();
    let dialogVisible = ref<boolean>(false);

    interface FiltersRow {
        value: number
        label: string
    }

    const exportDropdown = reactive<FiltersRow[]>([
        { value: 1, label: '全部导出' },
        { value: 2, label: '按入会时间' }
    ]);

    const exportConfig = reactive<TypeExport.Config>({
        title: '导出会员',
        name: '会员数据',
        body: { keyword: 'members_data' },
    });
    const showExportDialog = (row: FiltersRow) => {
        dialogVisible.value = true;
    }
</script>

<style scoped lang="scss">
    .table-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        overflow: hidden;
        border: 2px solid transparent;
    }

    .status-sign {
        width: 6px;
        height: 6px;
        margin-right: 4px;
        border-radius: 50%;
    }
</style>